import React from 'react';
import { connect } from 'dva';
import { InboxOutlined } from '@ant-design/icons';
// import { Form } from '@ant-design/compatible';
// import '@ant-design/compatible/assets/index.css';
import { Form, Button, Upload, Modal, Progress, message } from 'antd';
import router from 'umi/router';
import PropTypes from 'prop-types';
import downloadFile from '@/utils/utils';

const { Dragger } = Upload;

@connect()
// @Form.create()
class FileUpload extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      fileList: [],
    };
  }

  // 上传文件
  uploadFile = () => {
    const { uploadFile } = this.props;
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append('file', file);
    });
    uploadFile(formData);
  };

  /**
   * 默认上一步功能
   */
  preStep = () => {
    const { currentStep, setCurrentstep } = this.props;
    if (currentStep) {
      setCurrentstep(currentStep - 1);
    } else {
      router.goBack();
    }
  };

  render() {
    // 注释原代码，保留案发现场
    // const {
    //   uploadFileBtnText,
    //   currentStep,
    //   downloadTempInfo,
    //   uploading,
    //   progressTitle = '上传进度条',
    //   progressPercent,
    //   progressVisible,
    //   handleModalVisible,
    //   setCurrentstep,
    //   isExact,
    //   maskClosable = false,
    //   preStep = () => {
    //     if (currentStep) {
    //       setCurrentstep(currentStep - 1);
    //     } else {
    //       router.goBack();
    //     }
    //   },
    //   limitSize = 0, // 默认不限制，单位M
    //   fileTye = [
    //     // 默认限制类型，excel,传空数组表示不限制类型,或者传文件其他类型
    //     'application/vnd.ms-excel',
    //     'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    //     'xlsx',
    //     'xls',
    //   ],
    //   ExtraContent = null,
    // } = this.props;
    const {
      uploadFileBtnText,
      currentStep,
      downloadTempInfo,
      uploading,
      progressTitle,
      progressPercent,
      progressVisible,
      handleModalVisible,
      isExact,
      maskClosable,
      limitSize, // 默认不限制，单位M
      fileTye,
      ExtraContent,
    } = this.props;
    // 上一步props对象未提供用自己的
    const preStep = this.props.preStep ?? this.preStep;
    const { fileList } = this.state;
    const props = {
      beforeUpload: file => {
        if (limitSize) {
          const isLimitsize = file.size / 1024 / 1024 < limitSize; // 文件限制5M
          if (!isLimitsize) {
            return message.warning(
              `为了保证系统能够快速响应，上传文件大小不能超过${limitSize}M，如数据量太多，建议拆分后分批上传！`
            );
          }
        }
        if (fileTye.length) {
          const isType = !file.type ? file.name && file.name.split('.')[1] : file.type;
          const isExcel = fileTye.indexOf(isType) > -1;
          if (!isExcel) {
            return message.warning('文件格式错误，只能上传excel表格格式!');
          }
        }
        if (fileList.length === 1) {
          return message.warning('建议一次只能上传一个文件');
        }
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
    };

    return (
      <Form layout="horizontal">
        <div style={{ width: 480, height: 200, margin: '0 auto', marginTop: 50 }}>
          <Dragger {...props}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">点击或将文件拖拽到这里上传</p>
          </Dragger>
        </div>
        {ExtraContent && <ExtraContent />}
        <Modal
          title={progressTitle}
          footer={null}
          closable={false}
          maskClosable={maskClosable}
          visible={progressVisible}
          onCancel={() => handleModalVisible()}
        >
          <div style={{ textAlign: 'center' }}>
            <Progress percent={progressPercent} format={percent => `${percent}%`} />
          </div>
        </Modal>
        <div style={{ textAlign: 'center', marginTop: 100 }}>
          <Button onClick={() => preStep()} style={{ marginRight: 8 }}>
            {currentStep ? '上一步' : '返回'}
          </Button>
          <Button
            type="primary"
            style={{ marginRight: 8 }}
            onClick={() =>
              downloadFile(downloadTempInfo.params, downloadTempInfo.url, downloadTempInfo.type)
            }
          >
            下载模板
          </Button>
          <Button
            type="primary"
            onClick={this.uploadFile}
            disabled={fileList.length === 0}
            loading={uploading}
          >
            {uploadFileBtnText}
          </Button>
          {isExact ? <this.props.isExact /> : null}
        </div>
      </Form>
    );
  }
}

export default FileUpload;

FileUpload.propTypes = {
  uploadFileBtnText: PropTypes.string,
  currentStep: PropTypes.number.isRequired,
  downloadTempInfo: PropTypes.object.isRequired,
  uploading: PropTypes.bool.isRequired,
  uploadFile: PropTypes.func.isRequired,
  progressTitle: PropTypes.string,
  progressPercent: PropTypes.number.isRequired,
  progressVisible: PropTypes.bool.isRequired,
  handleModalVisible: PropTypes.func,
  setCurrentstep: PropTypes.func.isRequired,
  isExact: PropTypes.element,
  maskClosable: PropTypes.bool,
  preStep: PropTypes.func,
  limitSize: PropTypes.number,
  fileTye: PropTypes.array,
  ExtraContent: PropTypes.element,
};

FileUpload.defaultProps = {
  uploadFileBtnText: '提交',
  progressTitle: '上传进度条',
  handleModalVisible: () => {},
  isExact: null,
  maskClosable: false,
  preStep: null,
  limitSize: 0,
  fileTye: [
    // 默认限制类型，excel,传空数组表示不限制类型,或者传文件其他类型
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'xlsx',
    'xls',
  ],
  ExtraContent: null,
};
